<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="5" v-if="treeData.length != 0">
        <div style="padding: 20px;box-sizing: border-box;background: #fff;height: 80vh;">
          <div class="title">
            <div>机构列表</div>
          </div>
          <avue-tree ref="tree" style="margin-right: 20px;" :option="treeOption" @node-contextmenu="treeNodeContextmenu"
            :before-open="treeBeforeOpen" :filter="filterNodeMethod" @save="treeSave" @update="treeUpdate"
            :data="treeData" v-model="treeform" @del="treeDel" @node-click="treeNodeClick">
          </avue-tree>
        </div>
      </el-col>
      <el-col :span="treeData.length != 0?19:24"
        style="padding: 20px;box-sizing: border-box;background: #fff;height: 80vh;">
        <div class="title">
          <div>机构管理员</div>
        </div>
        <avue-crud :data="data" :option="option" @row-update="rowUpdate" @row-del="rowDel" @row-save="rowSave"
          :before-open="beforeOpen" v-model="form" @search-change="searchChange" @search-reset="searchReset">
          <template slot-scope="scope" slot="medPictureForm">
            <div class="block" style="width: 200px;">
              <el-image :src="form.medPicture" style="width: 200px;height:200px;">
                <div slot="error"
                  style="background: rgb(245, 247, 250); width: 100%;height: 100%;padding-top: 50px;box-sizing: border-box;overflow: hidden;color: #666;text-align: center;">
                  <i class="el-icon-plus"></i>
                  <div>点击上传图片</div>
                </div>
              </el-image>
              <div></div>
              <input class="imgBtn" type="file" accept="image/*" @change="handleFileChange">
            </div>

          </template>
          <template slot-scope="{row}" slot="disableFlag">
            <div>
              <el-tag v-if="!row.disableFlag" type="success">启用</el-tag>
              <el-tag v-else type="danger">停用</el-tag>

            </div>
          </template>
          <template slot-scope="{row,index}" slot="menu">

            <el-button v-if="!row.disableFlag && row.type == 2" type="text" size="small"
              @click="rowEnable(row,index)">停用</el-button>
            <el-button v-else type="text" size="small" @click="rowEnable(row,index)">启用</el-button>
            <el-button type="text" size="small" @click="rowDel(row,false)">
              <div :style="!row.disableFlag?'color: #666':''">删除</div>
            </el-button>
            <el-button v-if="row.type == 1" type="text" size="small" @click="rowEnable(row,index)">新增管理员</el-button>
          </template>
        </avue-crud>


        <el-dialog title="启用/停用" :visible.sync="deleteFlagVisible" width="30%" :before-close="handleClose">
          <el-select v-model="disableReason" placeholder="请选择">
            <el-option v-for="item in disableReasonOption" :key="item.snVal" :label="item.snName" :value="item.snVal">
            </el-option>
          </el-select>
          <span slot="footer" class="dialog-footer">
            <el-button @click="handleClose">取消</el-button>
            <el-button type="primary" @click="rowEnable({},0,true)">确认</el-button>
          </span>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import { dicIdList } from "@/api/com";
  import option from "@/const/mgmt/sys/org";
  import { orgMedical, orgOfficial, orgMedicalDetail, orgDel, } from "@/api/mgmt/sys/org";

  import { orgTree, orgOfficialDetail, orgOfficialUpdata, orgOfficialDel, orgOfficialAdd } from "@/api/mgmt/sys/org"


  export default {
    data() {
      return {
        data: [],
        allData: [],
        newData:[],
        option: option,
        form: {},
        query: {},
        treeData: [],
        treeform: {},
        treeOption: {
          defaultExpandAll: true,
          formOption: {
            labelWidth: 100,
            column: [ //机构--新增编辑字段
              {
                label: '机构名称',
                prop: 'officialName',
                hide: true,
                rules: [
                  { required: true, message: "请输入机构名称", trigger: "blur" },
                ],
                fieldType: 1
              },
              {
                label: '机构编码',
                prop: 'officialCode',
                hide: true,
                fieldType: 1
              },
              {
                label: '机构简称',
                prop: 'alias',
                hide: true,
                fieldType: 1
              },
              {
                label: '机构地址',
                prop: 'address',
                hide: true,

                fieldType: 1
              },
              {
                label: '机构电话',
                prop: 'phone',
                hide: true,
                rules: [
                  { required: true, message: "请输入机构电话", trigger: "blur" },
                ],
                fieldType: 1
              },
              {
                label: '机构属性',
                prop: 'attrName',
                type: 'select',
                props: {
                  label: 'snName',
                  value: 'snVal'
                },
                dicData: [],
                hide: true,
                fieldType: 2,
              }, {
                label: '机构分类',
                prop: 'typeName',
                type: 'select',
                props: {
                  label: 'snName',
                  value: 'snVal'
                },
                dicData: [],
                hide: true,
                fieldType: 2,
              },],
          },
          props: {
            labelText: '标题',
            label: 'name',
            value: 'id',
            children: 'children'
          }
        },
        deleteFlagVisible: false,
        disableReason: '',
        deleteFlagObj: {},
        pid: '',
        disableReasonOption: []
      }
    },
    mounted() {
      this.dicIdListFun();
      this.onLoad();
    },
    methods: {
      treeNodeClick(data, node, comp) {
        if (this.pid != data.id) {
          let newdata = this.allData.filter(item => item.pid === data.id);
          this.data = newdata;
          this.newData = this.data;
          this.form.officialPid = data.id;
          this.pid = data.id;
          
        } else {
          this.data = this.allData;
          this.newData = this.allData;
          this.pid = '';
        }

      },


      treeBeforeOpen(done, type) {
        if (['view', 'edit'].includes(type)) {
          // 查看和编辑逻辑
          console.log(this.treeform);
          orgOfficialDetail(this.treeform.id).then((res) => {
            this.treeform = res.data;
          })

        } else {

        }
        done()
      },
      treeNodeContextmenu(data, node, comp) {
        this.treeform = data;
      },
      filterNodeMethod(value, data) {
        console.log(value, data)
        return !value || data.label.indexOf(value) !== -1
      },
      treeSave(parent, data, done, loading) {
        this.treeform.offcialPid = 1;
        orgOfficialAdd(this.treeform).then(res => {
          this.$message.success("新增成功");
          this.onLoad();
          done();
        })
      },
      treeUpdate(parent, data, done, loading) {
        orgOfficialUpdata(this.treeform).then(res => {
          this.$message.success("修改成功");
          this.onLoad();
          done();
        })

      },
      treeDel() {
        this.rowDel(this.treeform, true)
      },
      dicIdListFun() {

        dicIdList('230,231,232,233,234,235,999,330').then(res => {


          /**
           * 机构
           * */
          //机构属性
          let attrName = this.findObject(this.treeOption.formOption.column, "attrName");
          attrName.dicData = res.list[0];
          //机构分类
          let typeName = this.findObject(this.treeOption.formOption.column, "typeName");
          typeName.dicData = res.list[1];

          /** 
           * 机构管理员
           * */
          //机构属性
          let medAttrId = this.findObject(this.option.column, "medAttrId");
          medAttrId.dicData = res.list[0];
          //机构分类
          let medTypeId = this.findObject(this.option.column, "medTypeId");
          medTypeId.dicData = res.list[1];
          //机构级别
          let medLevelId = this.findObject(this.option.column, "medLevelId");
          medLevelId.dicData = res.list[2];
          //会诊属性
          let consulAttrId = this.findObject(this.option.column, "consulAttrId");
          consulAttrId.dicData = res.list[3];
          //机构状态
          let medStatusId = this.findObject(this.option.column, "medStatusId");
          medStatusId.dicData = res.list[4];
          //住院收费级别
          let inpatChargeLevelId = this.findObject(this.option.column, "inpatChargeLevelId");
          inpatChargeLevelId.dicData = res.list[5];
          //门诊收费级别
          let outpatChargeLevelId = this.findObject(this.option.column, "outpatChargeLevelId");
          outpatChargeLevelId.dicData = res.list[5];

          //机构原因
          this.disableReasonOption = res.list[7];
        })
      },
      searchChange(params, done) {
        this.query = params;
        if (params.searchContent) {
          // 过滤表格数据
          if (this.pid) {
            this.data = this.newData.filter(item => item.name && item.name.toLowerCase().includes(params.searchContent));
          } else {
            this.data = this.allData.filter(item => item.name && item.name.toLowerCase().includes(params.searchContent) );
          }
        } else {
          this.data = this.allData;
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad();
      },
      onLoad() {
        orgTree({
          searchType: 1,
          searchContent: this.query.searchContent,
        }).then(res => {

          res.list.shift();
          // 按 type 字段分组
          let data = res.list.reduce((acc, item) => {
            if (!acc[item.type]) {
              acc[item.type] = [];
            }
            acc[item.type].push(item);
            return acc;
          }, {});

          this.treeData = Object.values(data[1] || {});

          let officialPid = this.findObject(this.option.column, "officialPid");
          officialPid.dicData = this.treeData;


          this.data = data[2];
          this.allData = data[2];
        })
      },

      handleFileChange(event) {
        const file = event.target.files[0];
        if (file) {
          const reader = new FileReader();
          reader.onload = (e) => {
            this.form.medPicture = e.target.result; // 将结果设置为预览图片的URL
          };
          reader.readAsDataURL(file); // 读取文件内容为DataURL
        }
      },
      rowEnable(row , index, show = false) {
        console.log(row, '原因',show)
        if (show) {
          if (!this.disableReason) {
            this.$message({
              type: "warning",
              message: "请输入停用原因!"
            });
            return;
          }
          this.rowEnableOfficial(this.deleteFlagObj)
        }

        if (!row.disableFlag) {
          this.deleteFlagVisible = true;
          this.deleteFlagObj = row;
          return;

        }
        this.$confirm(!row.disableFlag ? '是否确认停用?' : '是否确认启用?', {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.rowEnableOfficial(row)
        })
      },
      handleClose(done) {
        this.disableReason = '';
        this.deleteFlagVisible = false;
      },
      rowEnableOfficial(row) {
        orgOfficial({
          id: row.id,
          disableFlag: row.disableFlag ? 0 : 1,
          disableReason: this.disableReason
        }).then(res => {
          this.deleteFlagVisible = false;
          if (res.success) {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.onLoad();
          }
        })
      },
      rowSave(row, done, loading) {
        row.orgTypeId = 2;

        orgMedical(row).then(() => {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.onLoad();

          done();
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      beforeOpen(done, type) {
        console.log(this.form)
        if (["edit", "view"].includes(type)) {
          orgMedicalDetail(this.form.id).then(res => {
            this.form = res.data;
          });
        }
        done();
      },
      rowUpdate(row, index, done, loading) {
        console.log('修改')
        orgOfficial(row).then(() => {

          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.onLoad();
          done();
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row, show) {
      
        if (!show) {
          if (!row.disableFlag) {
            return;
          }
        }

        this.$confirm("是否确认删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return orgDel({
              id: row.id,
              orgTypeId: row.type
            });
          })
          .then(() => {
            this.onLoad();
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
    },
  }
</script>

<style>
  .imgBtn {
    opacity: 0;
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
    height: 100%;
    width: 100%
  }

  .title {
    padding-left: 10px;
    border-left: 4px solid #DC402B;
    margin-bottom: 22px;
  }
</style>